# coding=utf-8
# __author__ = "James Zhang"
# !/usr/bin/python
# -*- coding: utf-8 -*-
from core.sessions.exceptions import SuspiciousOperation
import core.utils.timezone as timezone
import base
from core.utils.encoding import force_text
import logging


class SessionStore(base.SessionBase):
    """
        使用方法:

        1. 创建Session:
        -------------------------------------------------------------
        > james = SessionStore()
        > james['username'] = 'jameszhang'
        > james.create()    # 将生成一个随机的session_key, 如: zoz0xikra78filgl74xdl5sdymojtzyu


        2. 查询,保存Session
        -------------------------------------------------------------
        > james = SessionStore('zoz0xikra78filgl74xdl5sdymojtzyu')
        > james['username']                 # 查询数据库,并将得到的结果缓存到本地
        #>> jameszhang
        > james.keys()                      # 不需查询数据库,调用本地缓存数据
        #>> ['username']
        > james['first_name'] = 'james'     # first_name为新增的key
        > james['last_name'] = 'zhang'      # last_name为新增的key
    """
    def __init__(self, session_key=None):
        super(SessionStore, self).__init__(session_key)

    def load(self):
        """
        加载session_key, 并返数据, 若无数据,返回空字典.

        :return:
        """
        try:
            s = Session.query.filter(Session.session_key == self.session_key,
                                     Session.expire_date > timezone.now()).first()
            return self.decode(s.session_data)
        except Exception as e:
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('tornado.security.%s' % e.__class__.__name__)
                logger.warning(force_text(e))
            self._session_key = None
            return {}

    def exists(self, session_key):
        """
        判断session_key是否存在:

        注意: session_key是一个主键

        :param session_key:
        :return: True/False
        """
        count = 0
        err = None
        while count < 3:
            try:
                res = Session.query.filter(Session.session_key == session_key).first()
                return bool(res)
            except Exception as e:
                Session.db.rollback()
                count += 1
                if count == 2:
                    err = e
        raise err

    def create(self):
        """
        生成一个唯一的session_key
        """
        while True:
            self._session_key = self._get_new_session_key()
            try:
                self.save(must_create=True)
            except base.CreateError:
                continue
            self.modified = True
            return

    def save(self, must_create=False):
        """
        :param must_create:
        :return:
        """
        if self.session_key is None:
            return self.create()
        if not must_create:
            db = Session.db
            try:
                db.query(Session).filter(Session.session_key == self._get_or_create_session_key()).update({
                    Session.session_data: self.encode(self._get_session(no_load=must_create)),
                    Session.expire_date: self.get_expiry_date()
                })
                db.commit()
                self.modified = False
            except:
                db.rollback()
        if must_create:
            obj = Session(
                session_key=self._get_or_create_session_key(),
                session_data=self.encode(self._get_session(no_load=must_create)),
                expire_date=self.get_expiry_date()
            )
            obj.save()
            self.modified = False

    def delete(self, session_key=None):
        """删除指定的session_key

        if session_key is None:
            if self.session_key is None:
                return
            session_key = self.session_key
        try:
            Session.objects.get(session_key=session_key).delete()
        except Session.DoesNotExist:
            pass


        :param session_key:
        :return:
        """
        if session_key is None:
            if self.session_key is None:
                return
            session_key = self.session_key
        try:
            Session.query.filter(Session.session_key == session_key).delete()
        except:
            pass

    @classmethod
    def clear_expired(cls):
        """
        清除所有无效的(expire_date时间小于当前时间)session
        :return:
        """
        try:
            Session.query.filter(Session.expire_date < timezone.now()).delete()
        except:
            pass


class RedisSessionStore(base.SessionBase):
    """
        待明天再更新......................

    """
    pass

# At bottom to avoid circular import
from core.sessions.models import Session
